package com.glsc.ngateway.platform.service.glres;

import cn.hutool.core.collection.CollectionUtil;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscSystemPartner;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscSystemResource;
import com.glsc.ngateway.common.base.domain.mysql.gateway.system.SystemMain;
import com.glsc.ngateway.common.base.domain.mysql.gateway.system.SystemMember;
import com.glsc.ngateway.common.base.enums.SystemMemberTypeEnum;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.glres.GlscSystemPartnerRepository;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.system.SystemMemberRepository;
import com.glsc.ngateway.platform.dto.GlscSystemPartnerDto;
import com.glsc.ngateway.platform.service.system.SystemMainService;
import com.glsc.ngateway.platform.utils.SpecificationUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GlscSystemPartnerService {

    @Resource
    private GlscSystemPartnerRepository glscSystemPartnerRepository;

    @Resource
    private GlscSystemResService glscSystemResService;

    @Resource
    private SystemMainService systemMainService;

    @Resource
    private SystemMemberRepository systemMemberRepository;

    /**
     * 分页查找
     *
     * @return
     */
    public Page<GlscSystemPartner> page(GlscSystemPartnerDto dto) {
        Map<String, Object> param = new HashMap<>();
        if (StringUtils.isNotBlank(dto.getPartnerName())) {
            param.put("LIKE_partnerName", dto.getPartnerName());
        }

        if (Objects.isNull(dto.getSystemId())) {
            PlatformResponse.successData(Page.empty());
        }
        if (Objects.isNull(dto.getPartnerType())) {
            PlatformResponse.successData(Page.empty());
        }

        if (dto.getSourceType().equals("2")) {
            //param.put("EQ_partnerType", dto.getPartnerType());
            param.put("EQ_sourceType", "1");
            param.put("EQ_partnerSourceType", "2");
            param.put("EQ_partnerSystemId", dto.getSystemId());
        } else {

            param.put("EQ_partnerType", dto.getPartnerType());
            param.put("EQ_sourceType", dto.getSourceType());
            param.put("EQ_systemId", dto.getSystemId());
        }


        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        Integer pageNo = PageUtil.initPageNo(dto.getPageNo());
        Integer pageSize = PageUtil.initPageSize(dto.getPageSize());

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<GlscSystemPartner> page = glscSystemPartnerRepository.findAll(SpecificationUtil.buildSpecification(param, GlscSystemPartner.class), pageable);
        List<GlscSystemPartner> contentList = Lists.newArrayList();
        if (Objects.nonNull(page)) {
            List<GlscSystemPartner> content = page.getContent();
            if (CollectionUtils.isNotEmpty(content)) {
                for (GlscSystemPartner partner : content) {
                    GlscSystemPartner partner1 = new GlscSystemPartner();
                    BeanUtils.copyProperties(partner,partner1);
                    partner1.setId(null);
                    contentList.add(partner1);
                }
            }

        }

        if (CollectionUtils.isNotEmpty(contentList)) {
            for (GlscSystemPartner partner : contentList) {
                if ("1".equals(partner.getPartnerSourceType())) {
                    SystemMain system = systemMainService.findSimpleInfoById(partner.getPartnerSystemId());
                    if (Objects.nonNull(system)) {
                        partner.setPartnerName(system.getOpName());
                        List<SystemMember> members = systemMemberRepository.findAll(Example.of(SystemMember.builder().opId(system.getOpId()).deleted(0).build()));
                        if (CollectionUtil.isNotEmpty(members)) {
                            List<String> memManager = members.stream().filter(e -> e.getMemberType().equals(SystemMemberTypeEnum.PROJECT_MANAGER.getCode())).map(SystemMember::getMemberName).collect(Collectors.toList());
                            partner.setSystemManage(StringUtils.join(memManager, ","));
                        }
                    }
                } else {
                    GlscSystemResource partnerSystem = glscSystemResService.findById(partner.getPartnerSystemId());
                    if (Objects.nonNull(partnerSystem)) {
                        partner.setPartnerName(partnerSystem.getName());
                        partner.setSystemManage(partnerSystem.getSystemManage());
                    }
                }
            }
        }


        if (dto.getSourceType().equals("2")) {
            if (CollectionUtils.isNotEmpty(contentList)) {
                for (GlscSystemPartner partner : contentList) {
                    SystemMain system = systemMainService.findSimpleInfoById(partner.getSystemId());
                    if (Objects.nonNull(system)) {
                        partner.setPartnerName(system.getOpName());
                        List<SystemMember> members = systemMemberRepository.findAll(Example.of(SystemMember.builder().opId(system.getOpId()).deleted(0).build()));
                        if (CollectionUtil.isNotEmpty(members)) {
                            List<String> memManager = members.stream().filter(e -> e.getMemberType().equals(SystemMemberTypeEnum.PROJECT_MANAGER.getCode())).map(SystemMember::getMemberName).collect(Collectors.toList());
                            partner.setSystemManage(StringUtils.join(memManager, ","));

                            Integer partnerSystemId = partner.getPartnerSystemId();
                            partner.setPartnerSystemId(partner.getSystemId());
                            partner.setSystemId(partnerSystemId);
                        }
                    }

                }
            }
        }
        return PageUtil.listConvertToPage(contentList,page.getPageable());
    }

    /**
     * 根据系统id查找所有的对接方信息
     *
     * @param systemId
     * @return
     */
    public List<GlscSystemPartner> listBySystemId(Integer systemId) {
        return glscSystemPartnerRepository.findAll(Example.of(GlscSystemPartner.builder().systemId(systemId).build()));
    }

    /**
     * 条件查找
     *
     * @param obj
     * @return
     */
    public List<GlscSystemPartner> listByCondition(GlscSystemPartner obj) {
        return glscSystemPartnerRepository.findAll(Example.of(obj));
    }

    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public GlscSystemPartner findById(Integer id) {
        Optional<GlscSystemPartner> optional = glscSystemPartnerRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 保存
     *
     * @param obj
     * @return
     */
    @Transactional
    public GlscSystemPartner save(GlscSystemPartner obj) {
        List<GlscSystemPartner> connectList = glscSystemPartnerRepository.findAll(Example.of(GlscSystemPartner.builder()
                .systemId(obj.getSystemId()).partnerSystemId(obj.getPartnerSystemId()).partnerType(obj.getPartnerType()).sourceType(obj.getSourceType()).build()));
        if (CollectionUtils.isNotEmpty(connectList) && connectList.get(0).getId() != obj.getId()) {
            Assert.isTrue(false, "系统对接信息已存在");
        }

        GlscSystemPartner oldPartner = null;
        if (Objects.nonNull(obj.getId())) {
            List<GlscSystemPartner> list = glscSystemPartnerRepository.findAll(Example.of(GlscSystemPartner.builder().systemId(obj.getPartnerSystemId()).partnerSystemId(obj.getSystemId())
                    .partnerType(obj.getPartnerType()).sourceType(obj.getSourceType()).build()));
            if (CollectionUtils.isNotEmpty(list)) {
                oldPartner = list.get(0);
            }
        }

//        GlscSystemPartner partner = GlscSystemPartner.builder().systemId(obj.getPartnerSystemId()).partnerSystemId(obj.getSystemId())
//                .deleted("N").build();

//        partnerSystemId(system.getId())
//        partnerType(partnerType)

//        partnerName(system.getName())
//        systemManage(system.getSystemManage())

        String partnerType = "";

        if ("1".equals(obj.getSourceType())) {
            //SystemMain system = systemMainService.findById(obj.getSystemId());
//            partner.setPartnerSourceType("1");
//            partner.setPartnerType("out_system");
            if ("in_middleware".equals(obj.getPartnerType())) {
                //GlscSystemResource partnerSystem = glscSystemResService.findById(obj.getPartnerSystemId());
//                partner.setSourceType("2");
                obj.setPartnerSourceType("2");
            } else {
//                partner.setSourceType("1");
                //SystemMain partnerSystem = systemMainService.findSimpleInfoById(obj.getPartnerSystemId());
                obj.setPartnerSourceType("1");

            }

        } else {
            //GlscSystemResource system = glscSystemResService.findById(obj.getSystemId());
//            partner.setPartnerSourceType("2");
//            partner.setPartnerType("out_system");
            if ("in_middleware".equals(obj.getPartnerType())) {
                //GlscSystemResource partnerSystem = glscSystemResService.findById(obj.getPartnerSystemId());
//                partner.setSourceType("2");
                obj.setPartnerSourceType("2");


            } else {
                //SystemMain partnerSystem = systemMainService.findSimpleInfoById(obj.getPartnerSystemId());
//                partner.setSourceType("1");
                obj.setPartnerSourceType("1");

            }
        }

        if (Objects.isNull(obj.getId())) {
            //新增建立双向关联关系
//            GlscSystemPartner systemPartner = findBySystemIdAndPartnerSystemId(partner.getSystemId(), partner.getPartnerSystemId());
//            if (Objects.nonNull(systemPartner)) {
//                partner.setId(systemPartner.getId());
//            }
//            glscSystemPartnerRepository.save(partner);
        } else {
            //修改则需要删除旧有关联关系，建立新的双向关联关系
            if (Objects.nonNull(oldPartner)) {
                oldPartner.setDeleted("Y");
                glscSystemPartnerRepository.save(oldPartner);
            }
        }
        glscSystemPartnerRepository.save(obj);
        return obj;
    }

    /**
     * 根据系统id和对接系统id查询
     *
     * @param systemId
     * @param partnerSystemId
     * @return
     */
    public GlscSystemPartner findBySystemIdAndPartnerSystemId(Integer systemId, Integer partnerSystemId) {
        List<GlscSystemPartner> list = glscSystemPartnerRepository.findAll(Example.of(GlscSystemPartner.builder().systemId(systemId).partnerSystemId(partnerSystemId).build()));
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }


    /**
     * 根据id删除
     *
     * @param id
     */
    public void delete(Integer id) {
        glscSystemPartnerRepository.deleteById(id);
    }
}
